
#include "httplib.h"
#include <nlohmann/json.hpp>
#include <mutex>

#include "logger.hpp"
#include "utils.hpp"

#include "mysql_blog.hpp"
#include "mysql_vlog.hpp"
#include "mysql_music.hpp"

// 存储活跃会话
static std::map<std::string, std::pair<std::string, std::chrono::system_clock::time_point>> sessions;

namespace zhiang {


#define BLOG_ADD                "/sora-service/blog/add"
#define BLOG_REMOVE             "/sora-service/blog/remove"
#define GET_BLOG_LIST           "/sora-service/blog/get_list"
#define GET_VLOG_LIST           "/sora-service/vlog/get_list"
#define VLOG_ADD                "/sora-service/vlog/add"
#define VLOG_REMOVE             "/sora-service/vlog/remove"
#define GET_MUSIC_LIST          "/sora-service/music/get_list"
#define MUSIC_ADD               "/sora-service/music/add"
#define MUSIC_REMOVE            "/sora-service/music/remove"

#define BLOG_ITEM_ADD_VIEW      "/sora-service/blog/add_view"
#define GET_BLOG_ITEMS          "/sora-service/blog/get_blog_items"
#define GET_VLOG                "/sora-service/vlog/get_vlog"

class GatewayServer {
private:
    
    class AuthHelper {
    public:
        // 从请求中提取token
        static std::string extractToken(const httplib::Request& request) {
            // 从Authorization头提取
            if (request.has_header("Authorization")) {
                std::string authHeader = request.get_header_value("Authorization");
                LOG_DEBUG("Authorization头: {}", authHeader);
                
                if (authHeader.find("Bearer ") == 0) {
                    return authHeader.substr(7); // 去掉"Bearer "前缀
                }
                return authHeader;
            }
            
            LOG_DEBUG("请求中没有Authorization头");
            return "";
        }
        
        // 验证token并返回username
        static std::string validateToken(const std::string& token) {
            if (token.empty()) {
                LOG_DEBUG("Token为空");
                return "";
            }
            
            LOG_DEBUG("验证token: {}", token);
            
            // 在sessions中查找token
            auto it = sessions.find(token);
            if (it == sessions.end()) {
                LOG_DEBUG("Token不存在于sessions中");
                return "";
            }
            
            // 检查token是否过期
            auto now = std::chrono::system_clock::now();
            if (now > it->second.second) {
                LOG_DEBUG("Token已过期");
                sessions.erase(it); // 移除过期的token
                return "";
            }
            
            // 返回用户名
            std::string username = it->second.first;
            LOG_DEBUG("Token验证成功，用户: {}", username);
            return username;
        }
        
        // 完整的认证检查
        static bool authenticateRequest(const httplib::Request& request, std::string& username) {
            std::string token = extractToken(request);
            if (token.empty()) {
                LOG_ERROR("请求中没有有效的token");
                return false;
            }
            
            username = validateToken(token);
            if (username.empty()) {
                LOG_ERROR("Token验证失败");
                return false;
            }
            
            LOG_DEBUG("用户认证成功: {}", username);
            return true;
        }
    };



public:
    using json = nlohmann::json;
    using ptr = std::shared_ptr<GatewayServer>;
private:
    void blogGet(const httplib::Request &request, httplib::Response &response) {
        auto errResp = [&](const std::string& msg)->void {
                json error_response;
                error_response["success"] = false;
                error_response["error"] = msg;
                response.status = 404;
                response.set_content(error_response.dump(), "application/json");
                LOG_ERROR("{}", msg);
                return;
            };
        try {
            // 解析JSON请求体
            auto json_body = json::parse(request.body);
            
            // 获取blog_ids数组
            std::vector<std::string> blog_ids;
            if (json_body.contains("blog_ids") && json_body["blog_ids"].is_array()) {
                for (const auto& id : json_body["blog_ids"]) {
                    if (!id.is_null()) {
                        blog_ids.push_back(id.get<std::string>());
                    }else if (id.is_number()) {
                        // 如果是数字，转换为字符串
                        blog_ids.push_back(std::to_string(id.get<int>()));
                    }
                }
            } else {
                return errResp("json 解析失败！");
            }
            
            if (blog_ids.empty()) {
                return errResp("得到的blog_id为空");
            }
            
            LOG_DEBUG("请求参数 blog_ids: {}", blog_ids.size());
            
            // 批量获取博客列表
            auto blogs = _mysql_blog->find(blog_ids);
            
            LOG_DEBUG("获取指定博客列表，数量：{}", blogs.size());
            
            // 构建响应JSON
            json response_json;
            response_json["success"] = true;
            response_json["data"] = json::array();
            
            for (auto& blog : blogs) {
                json blog_item;
                blog_item["blog_id"] = blog.blog_id();
                blog_item["title"] = blog.title();
                blog_item["intro"] = blog.intro();
                
                // 转换boost::posix_time::ptime为字符串
                std::string time_str;
                try {
                    auto create_time = blog.create_time();
                    std::stringstream ss;
                    ss << create_time;
                    time_str = ss.str();
                } catch (const std::exception& e) {
                    time_str = "未知时间";
                }
                blog_item["time"] = time_str;
                
                blog_item["view_count"] = blog.view_count();
                
                // 如果有其他字段，比如标签，可以在这里添加
                // blog_item["tags"] = blog.tags();
                
                // 构建文件路径
                std::string file_path = "./bin/data/blog/" + blog.blog_id() + "/index.html";
                blog_item["file_path"] = file_path;
                
                response_json["data"].push_back(blog_item);
            }
            
            LOG_DEBUG("构建响应JSON，包含 {} 个博客", response_json["data"].size());
            
            // 设置响应头
            response.set_header("Access-Control-Allow-Origin", "*");
            response.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.set_header("Access-Control-Allow-Headers", "Content-Type");
            
            // 发送响应
            response.set_content(response_json.dump(), "application/json");
            LOG_DEBUG("发送响应成功");
            
        } catch (const json::exception& e) {
            LOG_ERROR("JSON解析错误: {}", e.what());
            return errResp("Invalid JSON format");
        } catch (const std::exception& e) {
            LOG_ERROR("服务器内部错误: {}", e.what());
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Internal server error";
            error_response["details"] = e.what();
            response.status = 500;
            response.set_content(error_response.dump(), "application/json");
        }
    }

    void blogAddView(const httplib::Request &request, httplib::Response &response) {
        try {
            // 解析JSON请求体
            auto json_body = json::parse(request.body);
            auto errResp = [&](const std::string& msg)->void {
                json error_response;
                error_response["success"] = false;
                error_response["error"] = msg;
                response.status = 404;
                response.set_content(error_response.dump(), "application/json");
                return;
            };
            // 获取blog_id
            std::string blog_id;
            if (json_body.contains("blog_id") && !json_body["blog_id"].is_null()) {
                blog_id = json_body["blog_id"].get<std::string>();
            } else {
                return errResp("Missing blog_id");
            }
            LOG_DEBUG("请求参数 blog_id: {}", blog_id);
            json response_json;
            response_json["success"] = true;
            response_json["data"] = json::array();
            std::shared_ptr<Blog> blog = _mysql_blog->find(blog_id);
            if(!blog) {
                return errResp("mysql_blog not found id");
            }
            {
                std::unique_lock<std::mutex> lock(_mutex);
                blog->view_count(blog->view_count() + 1);
                LOG_DEBUG("blog_id: {} view_count: {}", blog->blog_id(), blog->view_count());
            }
            bool ret = _mysql_blog->update(*blog);
            if(!ret) {
                return errResp("mysql_blog update failed");
            }

            LOG_DEBUG("构建响应JSON");
            // 设置响应头
            response.set_header("Access-Control-Allow-Origin", "*");
            response.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.set_header("Access-Control-Allow-Headers", "Content-Type");
            LOG_DEBUG("设置响应头");
            
            // 发送响应
            response.set_content(response_json.dump(), "application/json");
            LOG_DEBUG("发送响应");
            
        } catch (const json::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Invalid JSON format";
            LOG_ERROR("{}", e.what());
            response.status = 400;
            response.set_content(error_response.dump(), "application/json");
        } catch (const std::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Internal server error";
            error_response["details"] = e.what();
            LOG_ERROR("{}", e.what());
            response.status = 500;
            response.set_content(error_response.dump(), "application/json");
        }
    }

    // 博客添加接口实现
    void blogAdd(const httplib::Request &request, httplib::Response &response) {
        LOG_DEBUG("开始处理博客上传请求");
        response.set_header("Access-Control-Allow-Origin", "*");
        response.set_header("Access-Control-Allow-Methods", "POST, OPTIONS");
        response.set_header("Access-Control-Allow-Headers", "Content-Type");
        
        // 处理预检请求
        if (request.method == "OPTIONS") {
            LOG_DEBUG("处理OPTIONS预检请求");
            response.status = 200;
            return;
        }
        
        // 检查是否为multipart/form-data请求
        if (!request.has_header("Content-Type")) {
            LOG_ERROR("缺少Content-Type头");
            response.status = 400;
            response.set_content(R"({"success": false, "error": "缺少Content-Type头"})", "application/json");
            return;
        }
        
        std::string contentType = request.get_header_value("Content-Type");
        LOG_DEBUG("Content-Type: {}", contentType);
        
        if (contentType.find("multipart/form-data") == std::string::npos) {
            LOG_ERROR("无效的Content-Type: {}，期望multipart/form-data", contentType);
            response.status = 400;
            response.set_content(R"({"success": false, "error": "无效的Content-Type，期望multipart/form-data"})", "application/json");
            return;
        }
        
        try {
            LOG_DEBUG("开始解析multipart表单数据");
            
            // 打印所有接收到的字段信息
            LOG_DEBUG("请求参数数量: {}", request.params.size());
            for (const auto& param : request.params) {
                LOG_DEBUG("参数: {} = {}", param.first, param.second);
            }
            
            LOG_DEBUG("文件字段数量: {}", request.files.size());
            for (const auto& file : request.files) {
                LOG_DEBUG("文件字段: {}, 文件名: {}, 大小: {} bytes", 
                        file.first, file.second.filename, file.second.content.size());
            }
            
            // 检查必需字段 - 在 multipart/form-data 中，普通字段也在 request.files 中
            std::string title, description;
            
            // 从 request.files 中获取普通字段
            auto titleIt = request.files.find("title");
            if (titleIt != request.files.end()) {
                title = titleIt->second.content;
                LOG_DEBUG("获取到标题: {}", title);
            } else {
                LOG_ERROR("缺少博客标题字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少博客标题"})", "application/json");
                return;
            }
            
            auto descriptionIt = request.files.find("description");
            if (descriptionIt != request.files.end()) {
                description = descriptionIt->second.content;
                LOG_DEBUG("获取到简介: {}", description);
            } else {
                LOG_ERROR("缺少博客简介字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少博客简介"})", "application/json");
                return;
            }
            
            // 检查必需文件 - 使用 request.files 获取上传的文件
            if (request.files.empty()) {
                LOG_ERROR("请求中没有文件字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少博客文件"})", "application/json");
                return;
            }
            
            // 查找博客HTML文件
            const httplib::MultipartFormData* htmlFile = nullptr;
            auto htmlFileIt = request.files.find("html");
            if (htmlFileIt != request.files.end()) {
                htmlFile = &htmlFileIt->second;
                LOG_DEBUG("找到HTML文件: {}, 大小: {} bytes", htmlFile->filename, htmlFile->content.size());
            } else {
                LOG_ERROR("缺少博客HTML文件字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少博客HTML文件"})", "application/json");
                return;
            }
            
            // 验证HTML文件类型
            if (!isValidExtension(htmlFile->filename, ".html")) {
                LOG_ERROR("HTML文件格式不支持: {}", htmlFile->filename);
                response.status = 400;
                response.set_content(R"({"success": false, "error": "只支持HTML格式文件"})", "application/json");
                return;
            }
            
            // 查找封面文件
            const httplib::MultipartFormData* coverFile = nullptr;
            auto coverFileIt = request.files.find("cover");
            if (coverFileIt != request.files.end()) {
                coverFile = &coverFileIt->second;
                LOG_DEBUG("找到封面文件: {}, 大小: {} bytes", coverFile->filename, coverFile->content.size());
            } else {
                LOG_ERROR("缺少封面文件字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少博客封面"})", "application/json");
                return;
            }
            
            // 验证封面图片类型
            if (!isValidExtension(coverFile->filename, ".jpg")) {
                LOG_ERROR("封面文件格式不支持: {}", coverFile->filename);
                response.status = 400;
                response.set_content(R"({"success": false, "error": "只支持JPG/PNG格式封面图片"})", "application/json");
                return;
            }
            
            // 查找内嵌图片文件（多个）
            std::vector<const httplib::MultipartFormData*> imageFiles;
            auto imageFilesRange = request.files.equal_range("images");
            for (auto it = imageFilesRange.first; it != imageFilesRange.second; ++it) {
                imageFiles.push_back(&it->second);
                LOG_DEBUG("找到内嵌图片文件: {}, 大小: {} bytes", it->second.filename, it->second.content.size());
            }
            LOG_DEBUG("找到 {} 个内嵌图片文件", imageFiles.size());
            
            // 验证内嵌图片类型
            for (const auto& imageFile : imageFiles) {
                if (!isValidExtension(imageFile->filename, ".jpg")) {
                    LOG_ERROR("内嵌图片文件格式不支持: {}", imageFile->filename);
                    response.status = 400;
                    response.set_content(R"({"success": false, "error": "只支持JPG格式内嵌图片"})", "application/json");
                    return;
                }
            }
            
            // 生成博客ID和封面图片ID
            std::string blogId = generate_uid();
            std::string coverImageId = zhiang::generate_uid();
            LOG_DEBUG("生成博客ID: {}, 封面图片ID: {}", blogId, coverImageId);
            
            // 创建博客目录
            std::string blogDir = "./data/blog/" + blogId;
            if (!std::filesystem::exists(blogDir)) {
                std::filesystem::create_directories(blogDir);
                LOG_DEBUG("创建博客目录: {}", blogDir);
            }
            
            // 保存HTML文件
            std::string htmlFilePath;
            if (!saveUploadedFile(*htmlFile, "index", blogDir, htmlFilePath)) {
                LOG_ERROR("保存HTML文件失败");
                response.status = 500;
                response.set_content(R"({"success": false, "error": "无法保存HTML文件"})", "application/json");
                return;
            }
            LOG_DEBUG("HTML文件保存成功: {}", htmlFilePath);
            
            // 保存封面图片
            std::string coverFilePath;
            if (!saveUploadedFile(*coverFile, coverImageId, blogDir, coverFilePath)) {
                // 如果封面保存失败，删除已保存的HTML文件
                LOG_ERROR("保存封面文件失败，删除已保存的HTML文件: {}", htmlFilePath);
                std::filesystem::remove(htmlFilePath);
                response.status = 500;
                response.set_content(R"({"success": false, "error": "无法保存封面图片"})", "application/json");
                return;
            }
            LOG_DEBUG("封面文件保存成功: {}", coverFilePath);
            
            // 保存内嵌图片
            std::vector<std::string> imageFilePaths;
            for (size_t i = 0; i < imageFiles.size(); ++i) {
                std::string imageId = zhiang::generate_uid();
                std::string imageFilePath;
                if (!saveUploadedFile(*imageFiles[i], imageId, blogDir, imageFilePath)) {
                    // 如果内嵌图片保存失败，删除已保存的所有文件
                    LOG_ERROR("保存内嵌图片文件失败，删除已保存的所有文件");
                    std::filesystem::remove(htmlFilePath);
                    std::filesystem::remove(coverFilePath);
                    for (const auto& savedImagePath : imageFilePaths) {
                        std::filesystem::remove(savedImagePath);
                    }
                    response.status = 500;
                    response.set_content(R"({"success": false, "error": "无法保存内嵌图片"})", "application/json");
                    return;
                }
                imageFilePaths.push_back(imageFilePath);
                LOG_DEBUG("内嵌图片文件保存成功: {}", imageFilePath);
            }
            
            // 创建Blog对象并保存到数据库
            // 注意：这里user_id暂时设为空，您可以根据需要从会话或token中获取
            zhiang::Blog blog(blogId, "");
            blog.title(title);
            blog.intro(description);
            blog.image_id(coverImageId);
            blog.view_count(0);
            blog.create_time(boost::posix_time::second_clock::local_time());
            
            LOG_DEBUG("创建Blog对象: ID={}, 标题={}, 简介={}, 封面ID={}", 
                    blogId, title, description, coverImageId);
            
            // 调用数据库插入方法
            // 假设您有一个 BlogTable 的实例 _mysql_blog
            LOG_DEBUG("开始插入数据库");
            bool insertSuccess = _mysql_blog->insert(blog);
            
            // 为了示例，我们假设插入成功
            // bool insertSuccess = true;
            
            if (insertSuccess) {
                LOG_DEBUG("数据库插入成功");
                response.status = 200;
                response.set_content(R"({"success": true, "message": "博客上传成功", "blog_id": ")" + blogId + "\"}", "application/json");
                LOG_INFO("博客上传成功: {} (ID: {})", title, blogId);
            } else {
                // 如果数据库插入失败，删除已保存的所有文件
                LOG_ERROR("数据库插入失败，删除已保存的所有文件");
                std::filesystem::remove(htmlFilePath);
                std::filesystem::remove(coverFilePath);
                for (const auto& imagePath : imageFilePaths) {
                    std::filesystem::remove(imagePath);
                }
                // 删除博客目录
                std::filesystem::remove_all(blogDir);
                
                response.status = 500;
                response.set_content(R"({"success": false, "error": "数据库插入失败"})", "application/json");
            }
            
        } catch (const std::exception& e) {
            LOG_ERROR("处理博客上传时发生异常: {}", e.what());
            response.status = 500;
            response.set_content(R"({"success": false, "error": "服务器内部错误"})", "application/json");
        }
        
        LOG_DEBUG("博客上传请求处理完成");
    }

    void blogRemove(const httplib::Request &request, httplib::Response &response) {
    }

    void blogList(const httplib::Request &request, httplib::Response &response) {
        try {
            // 解析JSON请求体
            auto json_body = json::parse(request.body);
            
            // 获取user_id
            std::string user_id;
            if (json_body.contains("user_id") && !json_body["user_id"].is_null()) {
                user_id = json_body["user_id"].get<std::string>();
            } else {
                json error_response;
                error_response["success"] = false;
                error_response["error"] = "Missing user_id";
                response.status = 400;
                response.set_content(error_response.dump(), "application/json");
                return;
            }
            LOG_DEBUG("请求参数 user_id: {}", user_id);
            // 获取数据库连接（这里需要您根据实际情况获取数据库实例）

            
            // 获取博客列表
            auto blogs = _mysql_blog->getBlogList(user_id);
            LOG_DEBUG("获取博客列表，数量：{}", blogs.size());
            // 构建响应JSON
            json response_json;
            response_json["success"] = true;
            response_json["data"] = json::array();
            
            for (const auto& blog : blogs) {
                json blog_item;
                blog_item["blog_id"] = blog.blog_id();
                blog_item["title"] = blog.title();
                blog_item["intro"] = blog.intro();
                
                // 转换boost::posix_time::ptime为字符串
                std::string time_str;
                try {
                    auto create_time = blog.create_time();
                    std::stringstream ss;
                    ss << create_time;
                    time_str = ss.str();
                
                } catch (const std::exception& e) {
                    time_str = "未知时间";
                }
                blog_item["time"] = time_str;
                
                blog_item["view_count"] = blog.view_count();
                
                // 构建文件路径
                std::string file_path = "./bin/data/blog/" + blog.blog_id() + "/index.html";
                blog_item["file_path"] = file_path;
                
                response_json["data"].push_back(blog_item);
            }
            LOG_DEBUG("构建响应JSON");
            // 设置响应头
            response.set_header("Access-Control-Allow-Origin", "*");
            response.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.set_header("Access-Control-Allow-Headers", "Content-Type");
            LOG_DEBUG("设置响应头");
            
            // 发送响应
            response.set_content(response_json.dump(), "application/json");
            LOG_DEBUG("发送响应");
            
        } catch (const json::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Invalid JSON format";
            LOG_ERROR("{}", e.what());
            response.status = 400;
            response.set_content(error_response.dump(), "application/json");
        } catch (const std::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Internal server error";
            error_response["details"] = e.what();
            LOG_ERROR("{}", e.what());
            response.status = 500;
            response.set_content(error_response.dump(), "application/json");
        }
    }
    void vlogAdd(const httplib::Request &request, httplib::Response &response) {}
    void vlogRemove(const httplib::Request &request, httplib::Response &response) {}
    void vlogList(const httplib::Request &request, httplib::Response &response) {
                try {
            // 解析JSON请求体
            auto json_body = json::parse(request.body);
            
            // 获取user_id
            std::string user_id;
            if (json_body.contains("user_id") && !json_body["user_id"].is_null()) {
                user_id = json_body["user_id"].get<std::string>();
            } else {
                json error_response;
                error_response["success"] = false;
                error_response["error"] = "Missing user_id";
                response.status = 400;
                response.set_content(error_response.dump(), "application/json");
                return;
            }
            LOG_DEBUG("请求参数 user_id: {}", user_id);
            
            // 获取博客列表
            auto vlogs = _mysql_vlog->getVlogList(user_id);
            LOG_DEBUG("获取vlog列表，数量：{}", vlogs.size());
            // 构建响应JSON
            json response_json;
            response_json["success"] = true;
            response_json["data"] = json::array();
            
            for (auto& vlog : vlogs) {
                json vlog_item;
                vlog_item["vlog_id"] = vlog.vlog_id();
                vlog_item["title"] = vlog.title();
                vlog_item["intro"] = vlog.intro();
                
                // 转换boost::posix_time::ptime为字符串
                std::string time_str;
                try {
                    auto create_time = vlog.create_time();
                    std::stringstream ss;
                    ss << create_time;
                    time_str = ss.str();
                
                } catch (const std::exception& e) {
                    time_str = "未知时间";
                }
                vlog_item["time"] = time_str;
                
                vlog_item["view_count"] = vlog.view_count();
                
                // 构建文件路径
                std::string file_path = "./bin/data/vlog/" + vlog.vlog_id() + ".jpg";
                vlog_item["file_path"] = file_path;
                
                response_json["data"].push_back(vlog_item);
            }
            LOG_DEBUG("构建响应JSON");
            // 设置响应头
            response.set_header("Access-Control-Allow-Origin", "*");
            response.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.set_header("Access-Control-Allow-Headers", "Content-Type");
            LOG_DEBUG("设置响应头");
            
            // 发送响应
            response.set_content(response_json.dump(), "application/json");
            LOG_DEBUG("发送响应");
            
        } catch (const json::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Invalid JSON format";
            LOG_ERROR("{}", e.what());
            response.status = 400;
            response.set_content(error_response.dump(), "application/json");
        } catch (const std::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Internal server error";
            error_response["details"] = e.what();
            LOG_ERROR("{}", e.what());
            response.status = 500;
            response.set_content(error_response.dump(), "application/json");
        }
    }
    
   // 音乐添加接口实现
    void musicAdd(const httplib::Request &request, httplib::Response &response) {

        LOG_DEBUG("开始处理音乐上传请求");
        response.set_header("Access-Control-Allow-Origin", "*");
        response.set_header("Access-Control-Allow-Methods", "POST, OPTIONS");
        response.set_header("Access-Control-Allow-Headers", "Content-Type");
        
        // 处理预检请求
        if (request.method == "OPTIONS") {
            LOG_DEBUG("处理OPTIONS预检请求");
            response.status = 200;
            return;
        }
        
        // 检查是否为multipart/form-data请求
        if (!request.has_header("Content-Type")) {
            LOG_ERROR("缺少Content-Type头");
            response.status = 400;
            response.set_content(R"({"success": false, "error": "缺少Content-Type头"})", "application/json");
            return;
        }
        
        std::string contentType = request.get_header_value("Content-Type");
        LOG_DEBUG("Content-Type: {}", contentType);
        
        if (contentType.find("multipart/form-data") == std::string::npos) {
            LOG_ERROR("无效的Content-Type: {}，期望multipart/form-data", contentType);
            response.status = 400;
            response.set_content(R"({"success": false, "error": "无效的Content-Type，期望multipart/form-data"})", "application/json");
            return;
        }

            // 验证用户认证
            std::string username;
            if (!AuthHelper::authenticateRequest(request, username)) {
                LOG_ERROR("用户认证失败");
                response.status = 401;
                response.set_content(R"({"success": false, "error": "用户未认证或token无效"})", "application/json");
                return;
            }
            
            LOG_DEBUG("用户认证成功，username: {}", username);
        
        try {
            LOG_DEBUG("开始解析multipart表单数据");
            
            // 打印所有接收到的字段信息
            LOG_DEBUG("请求参数数量: {}", request.params.size());
            for (const auto& param : request.params) {
                LOG_DEBUG("参数: {} = {}", param.first, param.second);
            }
            
            LOG_DEBUG("文件字段数量: {}", request.files.size());
            for (const auto& file : request.files) {
                LOG_DEBUG("文件字段: {}, 文件名: {}, 大小: {} bytes", 
                        file.first, file.second.filename, file.second.content.size());
            }
            
            // 检查必需字段 - 在 multipart/form-data 中，普通字段也在 request.files 中
            std::string title, author, time;
            
            // 从 request.files 中获取普通字段
            auto titleIt = request.files.find("title");
            if (titleIt != request.files.end()) {
                title = titleIt->second.content;
                LOG_DEBUG("获取到标题: {}", title);
            } else {
                LOG_ERROR("缺少音乐标题字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少音乐标题"})", "application/json");
                return;
            }
            
            auto authorIt = request.files.find("author");
            if (authorIt != request.files.end()) {
                author = authorIt->second.content;
                LOG_DEBUG("获取到作者: {}", author);
            } else {
                LOG_ERROR("缺少作者字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少作者信息"})", "application/json");
                return;
            }
            
            auto timeIt = request.files.find("time");
            if (timeIt != request.files.end()) {
                time = timeIt->second.content;
                time = std::to_string(std::stoi(time)/60) + "." + std::to_string(std::stoi(time)%60);
                LOG_DEBUG("获取到时長: {}", time);
            } else {
                LOG_ERROR("缺少时长字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少音乐时长"})", "application/json");
                return;
            }
            
            // 检查必需文件 - 使用 request.files 获取上传的文件
            if (request.files.empty()) {
                LOG_ERROR("请求中没有文件字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少音乐文件"})", "application/json");
                return;
            }
            
            // 查找音乐文件
            const httplib::MultipartFormData* musicFile = nullptr;
            auto musicFileIt = request.files.find("file");
            if (musicFileIt != request.files.end()) {
                musicFile = &musicFileIt->second;
                LOG_DEBUG("找到音乐文件: {}, 大小: {} bytes", musicFile->filename, musicFile->content.size());
            } else {
                LOG_ERROR("缺少音乐文件字段");
                response.status = 400;
                response.set_content(R"({"success": false, "error": "缺少音乐文件"})", "application/json");
                return;
            }
            
            // 验证音乐文件类型
            if (!isValidExtension(musicFile->filename, ".mp3")) {
                LOG_ERROR("音乐文件格式不支持: {}", musicFile->filename);
                response.status = 400;
                response.set_content(R"({"success": false, "error": "只支持MP3格式音乐文件"})", "application/json");
                return;
            }
            
            // 查找封面文件（可选）
            const httplib::MultipartFormData* coverFile = nullptr;
            auto coverFileIt = request.files.find("cover");
            if (coverFileIt != request.files.end()) {
                coverFile = &coverFileIt->second;
                LOG_DEBUG("找到封面文件: {}, 大小: {} bytes", coverFile->filename, coverFile->content.size());
            } else {
                LOG_DEBUG("未提供封面文件");
            }
            
            // 验证封面图片类型（如果提供了封面）
            if (coverFile && !isValidExtension(coverFile->filename, ".jpg")) {
                LOG_ERROR("封面文件格式不支持: {}", coverFile->filename);
                response.status = 400;
                response.set_content(R"({"success": false, "error": "只支持JPG格式封面图片"})", "application/json");
                return;
            }
            
            // 生成音乐ID
            std::string musicId = generate_uid();
            LOG_DEBUG("生成音乐ID: {}", musicId);
            
            // 保存音乐文件
            std::string musicFilePath;
            if (!saveUploadedFile(*musicFile, musicId, "./data/music", musicFilePath)) {
                LOG_ERROR("保存音乐文件失败");
                response.status = 500;
                response.set_content(R"({"success": false, "error": "无法保存音乐文件"})", "application/json");
                return;
            }
            LOG_DEBUG("音乐文件保存成功: {}", musicFilePath);
            
            // 保存封面图片（如果提供了）
            std::string coverFilePath;
            if (coverFile) {
                if (!saveUploadedFile(*coverFile, musicId, "./data/music", coverFilePath)) {
                    // 如果封面保存失败，删除已保存的音乐文件
                    LOG_ERROR("保存封面文件失败，删除已保存的音乐文件: {}", musicFilePath);
                    std::filesystem::remove(musicFilePath);
                    response.status = 500;
                    response.set_content(R"({"success": false, "error": "无法保存封面图片"})", "application/json");
                    return;
                }
                LOG_DEBUG("封面文件保存成功: {}", coverFilePath);
            }
            
            // 创建Music对象并保存到数据库
            zhiang::Music music(musicId, time, title, author);
            LOG_DEBUG("创建Music对象: ID={}, 标题={}, 作者={}, 时长={}", musicId, title, author, time);
            
            // 调用数据库插入方法
            LOG_DEBUG("开始插入数据库");
            bool insertSuccess = _mysql_music->insert(music);
            
            if (insertSuccess) {
                LOG_DEBUG("数据库插入成功");
                response.status = 200;
                response.set_content(R"({"success": true, "message": "音乐上传成功", "music_id": ")" + musicId + "\"}", "application/json");
                LOG_INFO("音乐上传成功: {} - {} (ID: {})", title, author, musicId);
            } else {
                // 如果数据库插入失败，删除已保存的文件
                LOG_ERROR("数据库插入失败，删除已保存的文件");
                std::filesystem::remove(musicFilePath);
                if (coverFile) {
                    std::filesystem::remove(coverFilePath);
                }
                
                response.status = 500;
                response.set_content(R"({"success": false, "error": "数据库插入失败"})", "application/json");
            }
            
        } catch (const std::exception& e) {
            LOG_ERROR("处理音乐上传时发生异常: {}", e.what());
            response.status = 500;
            response.set_content(R"({"success": false, "error": "服务器内部错误"})", "application/json");
        }
        
        LOG_DEBUG("音乐上传请求处理完成");
    }

    void musicRemove(const httplib::Request &request, httplib::Response &response) {}

    void musicList(const httplib::Request &request, httplib::Response &response) {
                try {
            // 解析JSON请求体
            // auto json_body = json::parse(request.body);
        
            // 获取博客列表
            auto musics = _mysql_music->getMusicList();
            LOG_DEBUG("获取Muisc列表，数量：{}", musics.size());
            // 构建响应JSON
            json response_json;
            response_json["success"] = true;
            response_json["data"] = json::array();
            
            for (auto& music : musics) {
                json music_item;
                music_item["music_id"] = music.music_id();
                music_item["title"] = music.title();
                music_item["author"] = music.author();
                music_item["time"] = music.time();
                
                response_json["data"].push_back(music_item);
            }
            LOG_DEBUG("构建响应JSON");
            // 设置响应头
            response.set_header("Access-Control-Allow-Origin", "*");
            response.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.set_header("Access-Control-Allow-Headers", "Content-Type");
            LOG_DEBUG("设置响应头");
            
            // 发送响应
            response.set_content(response_json.dump(), "application/json");
            LOG_DEBUG("发送响应");
            
        } catch (const json::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Invalid JSON format";
            LOG_ERROR("{}", e.what());
            response.status = 400;
            response.set_content(error_response.dump(), "application/json");
        } catch (const std::exception& e) {
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Internal server error";
            error_response["details"] = e.what();
            LOG_ERROR("{}", e.what());
            response.status = 500;
            response.set_content(error_response.dump(), "application/json");
        }
    }

    void vlog_get(const httplib::Request &request, httplib::Response &response) {
        auto errResp = [&](const std::string& msg)->void {
                json error_response;
                error_response["success"] = false;
                error_response["error"] = msg;
                response.status = 404;
                response.set_content(error_response.dump(), "application/json");
                LOG_ERROR("{}", msg);
                return;
            };
        try {
            // 解析JSON请求体
            auto json_body = json::parse(request.body);
            std::string vlog_id = json_body["vlog_id"];
            LOG_DEBUG("请求参数 vlog_id: {}", vlog_id);
            
            // 批量获取博客列表
            auto vlog = _mysql_vlog->find(vlog_id);
            if(!vlog) {
                return errResp("mysql_blog not found id");
            }
            
            // 构建响应JSON
            json response_json;
            response_json["success"] = true;
            
            
            json vlog_item;
            vlog_item["vlog_id"] = vlog->vlog_id();
            vlog_item["title"] = vlog->title();
            vlog_item["intro"] = vlog->intro();
            // 转换boost::posix_time::ptime为字符串
            std::string time_str;
            try {
                auto create_time = vlog->create_time();
                std::stringstream ss;
                ss << create_time;
                time_str = ss.str();
            } catch (const std::exception& e) {
                time_str = "未知时间";
            }
            vlog_item["time"] = time_str;   
            vlog_item["view_count"] = vlog->view_count();
            vlog_item["link"] = vlog->link();
            response_json["data"] = vlog_item;
            
            // 设置响应头
            response.set_header("Access-Control-Allow-Origin", "*");
            response.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            response.set_header("Access-Control-Allow-Headers", "Content-Type");
            
            // 发送响应
            response.set_content(response_json.dump(), "application/json");
            LOG_DEBUG("发送响应成功");
            
        } catch (const json::exception& e) {
            LOG_ERROR("JSON解析错误: {}", e.what());
            return errResp("Invalid JSON format");
        } catch (const std::exception& e) {
            LOG_ERROR("服务器内部错误: {}", e.what());
            json error_response;
            error_response["success"] = false;
            error_response["error"] = "Internal server error";
            error_response["details"] = e.what();
            response.status = 500;
            response.set_content(error_response.dump(), "application/json");
        }
    }

    // 生成随机Token
    std::string generate_token() {
        static const char alphanum[] =
            "0123456789"
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            "abcdefghijklmnopqrstuvwxyz";
        
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, sizeof(alphanum) - 2);
        
        std::string token;
        for (int i = 0; i < 32; ++i) {
            token += alphanum[dis(gen)];
        }
        return token;
    }

    // 检查Token是否有效
    bool is_token_valid(const std::string& token) {
        auto it = sessions.find(token);
        if (it == sessions.end()) return false;
        
        // 检查Token是否过期（设置为1小时）
        auto now = std::chrono::system_clock::now();
        auto expiry_time = it->second.second;
        
        return now < expiry_time;
    }

    // 获取用户名
    std::string get_username_from_token(const std::string& token) {
        auto it = sessions.find(token);
        if (it != sessions.end()) {
            return it->second.first;
        }
        return "";
    }

public:
    GatewayServer(const int http_port, const std::shared_ptr<odb::core::database>& mysql_client) :
        _http_port(http_port),
        _mysql_blog(std::make_shared<BlogTable>(mysql_client)),
        _mysql_vlog(std::make_shared<VlogTable>(mysql_client)),
        _mysql_music(std::make_shared<MusicTable>(mysql_client)),
        _http_server(std::make_shared<httplib::Server>()) {
        
            // 设置CORS头，允许前端跨域请求
        _http_server->set_default_headers({
            {"Access-Control-Allow-Origin", "*"},
            {"Access-Control-Allow-Methods", "POST, GET, OPTIONS"},
            {"Access-Control-Allow-Headers", "Content-Type"}
        });
        
        // 处理预检请求
        _http_server->Options(R"(.*)", [](const httplib::Request&, httplib::Response& res) {
            res.set_header("Access-Control-Allow-Origin", "*");
            res.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            res.set_header("Access-Control-Allow-Headers", "Content-Type");
        });
        
        // 静态文件服务（提供前端页面）
        _http_server->set_mount_point("/", "./");

        _http_server->Post(BLOG_ADD       , (httplib::Server::Handler)std::bind(&GatewayServer::blogAdd, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(BLOG_REMOVE    , (httplib::Server::Handler)std::bind(&GatewayServer::blogRemove, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(GET_BLOG_LIST  , (httplib::Server::Handler)std::bind(&GatewayServer::blogList, this, std::placeholders::_1, std::placeholders::_2));
        
        _http_server->Post(VLOG_ADD     , (httplib::Server::Handler)std::bind(&GatewayServer::vlogAdd, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(VLOG_REMOVE  , (httplib::Server::Handler)std::bind(&GatewayServer::vlogRemove, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(GET_VLOG_LIST, (httplib::Server::Handler)std::bind(&GatewayServer::vlogList, this, std::placeholders::_1, std::placeholders::_2));

        _http_server->Post(MUSIC_ADD     , (httplib::Server::Handler)std::bind(&GatewayServer::musicAdd, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(MUSIC_REMOVE  , (httplib::Server::Handler)std::bind(&GatewayServer::musicRemove, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(GET_MUSIC_LIST, (httplib::Server::Handler)std::bind(&GatewayServer::musicList, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(BLOG_ITEM_ADD_VIEW   , (httplib::Server::Handler)std::bind(&GatewayServer::blogAddView, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(GET_BLOG_ITEMS   , (httplib::Server::Handler)std::bind(&GatewayServer::blogGet, this, std::placeholders::_1, std::placeholders::_2));
        _http_server->Post(GET_VLOG         , (httplib::Server::Handler)std::bind(&GatewayServer::vlog_get, this, std::placeholders::_1, std::placeholders::_2));

        _http_server->set_payload_max_length(100 * 1024 * 1024);
        // 登录接口
        _http_server->Post("/sora-service/login", [&](const httplib::Request& req, httplib::Response& res) {
            try {
            std::cout << "接受请求login\n";
                auto json_body = json::parse(req.body);
                std::string username = json_body["username"];
                std::string password = json_body["password"];
                bool remember = json_body.value("remember", false);
                
                // 验证用户名和密码
                auto user_it = users.find(username);
                if (user_it != users.end() && user_it->second == password) {
                    // 生成Token
                    std::string token = generate_token();
                    
                    // 设置过期时间（1小时或7天，如果选择"记住我"）
                    auto expiry_duration = remember ? 
                        std::chrono::hours(24 * 7) : // 7天
                        std::chrono::hours(1);       // 1小时
                    
                    auto expiry_time = std::chrono::system_clock::now() + expiry_duration;
                    
                    // 存储会话
                    sessions[token] = make_pair(username, expiry_time);
                    
                    // 返回成功响应
                    json response = {
                        {"success", true},
                        {"user", username},
                        {"token", token},
                        {"expires_at", std::chrono::system_clock::to_time_t(expiry_time)}
                    };
                    
                    res.set_content(response.dump(), "application/json");
                } else {
                    json response = {
                        {"success", false},
                        {"message", "用户名或密码错误"}
                    };
                    res.set_content(response.dump(), "application/json");
                }
            } catch (const std::exception& e) {
                json response = {
                    {"success", false},
                    {"message", "请求格式错误"}
                };
                res.set_content(response.dump(), "application/json");
            }
        });
        
        // 检查登录状态接口
        _http_server->Get("/sora-service/check_login", [&](const httplib::Request& req, httplib::Response& res) {
            std::string token = req.get_header_value("Authorization");
            std::cout << "接受请求check login\n";
            std::cout << "已登录用户：" ;
            for(const auto& [a, b] : sessions) std::cout << "a  " ;
            std::cout << "\n";
            if (!token.empty() && token.find("Bearer ") == 0) {
                token = token.substr(7); // 移除"Bearer "前缀
            }
            
            if (is_token_valid(token)) {
                std::string username = get_username_from_token(token);
                auto expiry_time = sessions[token].second;
                
                json response = {
                    {"logged_in", true},
                    {"user", username},
                    {"expires_at", std::chrono::system_clock::to_time_t(expiry_time)}
                };
                res.set_content(response.dump(), "application/json");
            } else {
                json response = {
                    {"logged_in", false}
                };
                res.set_content(response.dump(), "application/json");
            }
        });
        
        // 退出登录接口
        _http_server->Post("/sora-service/logout", [&](const httplib::Request& req, httplib::Response& res) {
            std::string token = req.get_header_value("Authorization");
            std::cout << "接受请求logout\n";
            
            if (!token.empty() && token.find("Bearer ") == 0) {
                token = token.substr(7); // 移除"Bearer "前缀
            }
            
            if (!token.empty()) {
                sessions.erase(token);
            }
            
            json response = {
                {"success", true}
            };
            res.set_content(response.dump(), "application/json");
        });
    }
 

    void start() {
        
        _http_server->listen("0.0.0.0", _http_port);
    }
private:
    int _http_port;
    std::shared_ptr<httplib::Server> _http_server;
    std::shared_ptr<BlogTable> _mysql_blog;
    std::shared_ptr<VlogTable> _mysql_vlog;
    std::shared_ptr<MusicTable> _mysql_music;
    std::mutex _mutex;

    // 简单的用户存储（实际应用中应使用数据库）
    std::map<std::string, std::string> users = {
        {"admin", "password123"},
        {"user1", "pass123"},
        {"test", "test123"},
        {"zhiang", "123"}
    };


};

class GatewayBuilder {
public:
    GatewayBuilder() {}
    ~GatewayBuilder() {}
   
    void make_mysql_client(const std::string& user, const std::string& pswd, 
        std::string& db, const std::string& host, int port, 
        const std::string& cset, int connect_pool_count) {
        _mysql_client = ODBFactory::create(user, pswd, db, host, port, cset, connect_pool_count);
    }

    void make_http_object(int http_port) {
        _http_port = http_port;
    }

    GatewayServer::ptr build() {
        if(!_mysql_client) {
            LOG_ERROR("Gateway服务_mysql_client初始化失败");
            exit(-1);
        }
        if(_http_port < 0) {
            LOG_ERROR("Gateway服务_http初始化失败");
            exit(-1);
        }
        return std::make_shared<GatewayServer>(_http_port, _mysql_client);
    }
private:
    int _http_port = -1;
    std::shared_ptr<odb::core::database> _mysql_client;
};

}

